var express = require('express');
var router = express.Router();
var sqlite3 = require('sqlite3').verbose();
var path = require('path');
/* GET users listing. */
router.get('/', function(req, res, next) {
    var db=new sqlite3.Database(path.join(__dirname, "../db/LH.s3db"));
    if(req.query.isJoin=='yes'){
        try{
            var year = req.query.time.substring(0,4);
            var month = req.query.time.split('/')[1];
            if(month>=9){
                var time = year+"-"+(year+1);
            }else{
                var time = (year-1)+"-"+(year);
            }
            sqlStr1 = "INSERT INTO s_activity values(?,?,0,?,-1,?,'')";
            sqlStr2 = "UPDATE activity SET s_num = s_num + 1 where a_no = ? "
            db.all(sqlStr1, [req.session.username,req.query.a_no,req.query.time,time],function(err){
                if(err!=null){
                    res.send('0');
                }else{
                    db.all(sqlStr2, [req.query.a_no],function(err){
                        if(err!=null){
                            res.send('0');
                        }else{
                            res.send('1');
                        }
                    } );
                }
            } );
        }catch(ex){
            console.log(ex);
        }
    }
    else if(req.query.isJoin=='no'){
        try{
            sqlStr1 = "DELETE FROM s_activity WHERE s_id = ? and a_no = ?";
            sqlStr2 = "UPDATE activity SET s_num = s_num - 1 where a_no = ? "
            db.all(sqlStr1, [req.session.username,req.query.a_no],function(err){
                if(err!=null){
                    res.send('0');
                }else{
                    db.all(sqlStr2, [req.query.a_no],function(err){
                        if(err!=null){
                            res.send('0');
                        }else{
                            res.send('1');
                        }
                    } );
                }
            } );
        }catch(ex){
            console.log(ex);
        }
    }
});

module.exports = router;
